package com.alpaak.aspect;

import com.alpaak.common.annotation.DataSource;
import com.alpaak.common.constants.DataSourceConstant;
import com.alpaak.common.utils.DataSourceContextHolder;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

/**
 * @ClassName: DataSourceAspect
 * @Description: 数据源切换aspect（若启用数据库的事务管理，需要在数据库事务开启切换数据库，
 *               否则数据库的切换只能在下次数据库操作时才生效。）
 * @author eason
 * @date 2018年2月26日 下午4:48:57
 */
public class DataSourceAspect implements MethodBeforeAdvice, AfterReturningAdvice {

	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		DataSourceContextHolder.clearDataSourceType();
	}

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {

		if (method.isAnnotationPresent(DataSource.class)) {
			DataSource datasource = method.getAnnotation(DataSource.class);
			DataSourceContextHolder.setDataSourceType(datasource.name());
		} else {
			DataSourceContextHolder.setDataSourceType(DataSourceConstant.DATASOURCE1);
		}

	}

}
